package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.constants.UserConstant;
import cn.edu.gzhu.workOrderManagement.mapper.UserMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.user.UserDeleteDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.User;
import cn.edu.gzhu.workOrderManagement.wrapper.CachedBodyHttpServletRequestWrapper;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 这是一个授权拦截器只拦截 /user/deleteUsers 路径的请求,位于拦截器链的第二位
 * @author chen xi
 */

@Component
@Slf4j
public class DeleteUserInterceptor implements HandlerInterceptor {
    @Autowired
    UserMapper userMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CachedBodyHttpServletRequestWrapper wrapper = new CachedBodyHttpServletRequestWrapper(request);
        String body = wrapper.getBody();
        UserDeleteDto userDeleteDto = JSONUtil.toBean(body, UserDeleteDto.class);


        List<String> usernames = userDeleteDto.getUsernames();
        Claims claims = (Claims) request.getAttribute("claims");

        // 拒绝普通用户调用
        if (claims.get("authority").equals(UserConstant.COMMON_USER)){
            response.setStatus(401);
            return false;
        }
        //负责人权限策略
        if (claims.get("authority").equals(UserConstant.SUPERINTENDENT)){
            for (String username : usernames) {
                List<User> users = userMapper.listByConditions(User.builder().username(username).build());
                User user = users.get(0);
                //拒绝负责人删除非本组织用户
                if (!user.getOrganization().equals(claims.get("organization"))) {
                    response.setStatus(401);
                    return false;
                }
                //拒绝负责人删除其它负责人和管理员
                if (user.getAuthority().equals(UserConstant.SUPERINTENDENT) ||
                        user.getAuthority().equals(UserConstant.ADMIN)) {
                    response.setStatus(401);
                    return false;
                }
            }
        }
        log.info("放行");
        return true;

    }

}

